import {
  getSong
} from '../../api/singer'
import {
  getSongKuGou,
  getLyricKuGou
} from '../../api/search'
import {
  getSonglyric
} from 'api/song'
import {
  ERR_OK
} from 'api/config'
import {
  b64DecodeUnicode
} from './dom'
// import {getSong} from 'api/singer'
export default class Song {
  constructor(config) {
    for (const key in config) {
      if (config.hasOwnProperty(key)) {
        this[key] = config[key]
      }
    }
  }
  // 获取歌词
  async getLyric() {
    if (this.lyric) return Promise.resolve(this.lyric)
    const res = await getSonglyric(this.songmid)
    if (ERR_OK === res.retcode) {
      this.lyric = b64DecodeUnicode(res.lyric)
      return Promise.resolve(this.lyric)
    }
  }
}
// QQ 音乐创建歌曲
export async function createSong(musicData, i) {
  let url = await handleSongUrl(musicData.songmid)
  return new Song({
    index: i,
    id: musicData.songid,
    // 专辑名
    albumname: musicData.albumname,
    // 歌名
    songname: musicData.songname,
    time: musicData.interval,
    songmid: musicData.songmid,
    // 歌手
    singer: handleSinger(musicData.singer),
    // 歌曲图片
    image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
    // 歌曲地址
    songUrl: url
  })
}
// 获取歌曲地址
function handleSongUrl(mid) {
  return new Promise((resolve, reject) => {
    getSong(mid).then((res) => {
      let purl = res.req_0.data.midurlinfo[0].purl
      resolve(`http://113.96.98.156/amobile.music.tc.qq.com/${purl}`)
    }).catch((err) => {
      reject(err)
    })
  })
}

// 输出 薛之谦/郭襄
function handleSinger(singer) {
  let ret = []
  if (!singer) return ''
  singer.forEach(item => {
    ret.push(item.name)
  })
  return ret.join('/')
}

// 酷狗音乐创建歌曲
export async function createSongKuGou(hash, i) {
  let res = await getSongKuGou(hash)
  let lyric = await getLyricKuGou(hash, res.fileName, res.timeLength * 1000)
  return new Song({
    index: i,
    id: res.hash,
    filename: res.fileName,
    // 专辑名
    albumname: '',
    // 歌名
    songname: res.songName,
    time: res.timeLength,
    songmid: '',
    // 歌手
    singer: res.singerName,
    // 歌曲图片
    image: res.imgUrl.replace(/\{size\}/, 200),
    // 歌曲地址
    songUrl: res.url,
    lyric
  })
}
